import requests
import datetime
import hashlib
import mimetypes
import services
import os
from werkzeug.datastructures import FileStorage
from configs import dify_config
import services
from services.file_service import FileService
from controllers.service_api.app.error import (
    FileTooLargeError,
    NoFileUploadedError,
    TooManyFilesError,
    UnsupportedFileTypeError,
)
import uuid
from extensions.ext_database import db
from extensions.ext_storage import storage
from models.model import EndUser, UploadFile
from models.enums import CreatedByRole

random_uuid = str(uuid.uuid4())

def get_assiantprofile():
    url = "https://api.coze.cn/v1/workflow/run"
    headers = {
        "Authorization": "Bearer pat_cD8BX3lBD0EVygwS58V7tEFbOkXOh2Id6Mwz2b53jdfedOMKoozWwZmkISLVEVuX",
        "Content-Type": "application/json"
    }
    payload = {
        "parameters": {
            "query": "新闻调研助手"
        },
        "workflow_id": "7507070062289879079"
    }
    response = requests.post(url, headers=headers, json=payload)
    return response


def download_image(url, save_path):
    try:
        response = requests.get(url, stream=True)
        response.raise_for_status()  # 检查请求是否成功
        with open(save_path, 'wb') as file:
            for chunk in response.iter_content(1024):
                file.write(chunk)
        print(f"图片已保存到 {save_path}")
    except Exception as e:
        print(f"下载失败: {e}")


def upload_image(filepath,tenant_id,user_id):
    """上传本地图片文件到文件服务"""
    if not os.path.exists(filepath):
        raise FileNotFoundError(f"File not found: {filepath}")
    
    filename = os.path.basename(filepath)
    mimetype = mimetypes.guess_type(filename)[0] or 'application/octet-stream'
    
    # 先读取文件内容
    with open(filepath, 'rb') as f:
        content = f.read()
        extension = filename.split(".")[-1].lower()
        if len(filename) > 200:
            filename = filename.split(".")[0][:200] + "." + extension

        # get file size
        file_size = len(content)

        # check if the file size is exceeded
        if not FileService.is_file_size_within_limit(extension=extension, file_size=file_size):
            raise FileTooLargeError

        # generate file key
        file_uuid = str(uuid.uuid4())

        file_key = "upload_files/" + (tenant_id or "") + "/" + file_uuid + "." + extension

        # save file to storage
        storage.save(file_key, content)

        # save file to db
        upload_file = UploadFile(
            tenant_id=tenant_id or "",
            storage_type=dify_config.STORAGE_TYPE,
            key=file_key,
            name=filename,
            size=file_size,
            extension=extension,
            mime_type=mimetype,
            created_by_role=CreatedByRole.ACCOUNT,
            created_by=user_id,
            created_at=datetime.datetime.now(datetime.UTC).replace(tzinfo=None),
            used=False,
            hash=hashlib.sha3_256(content).hexdigest(),
            source_url="",
        )

        db.session.add(upload_file)
        db.session.commit()

        return upload_file